<template>
  <view class="search-back">
    <view class="search-container">
      <view v-if="deviceSearch" class="search-text">
        <text class="bold-text">正在搜索可用设备...</text>
        <text class="small-text">请确保设备以及开机（点击非白色部分可关闭）</text>
				<view class="radar-container">
				  <blog-radar-core :start-animation="true" :size="160"></blog-radar-core>
				</view>
      </view>
      <view v-else>设备名称：{{ device }}</view>
			<view v-if="deviceFind">
				<image v-if="device=='血压仪器'" src="../../static/images/blood_presure_device.png"></image>
				<image v-else-if="device=='血氧仪器'" src="../../static/images/blood_oxygen.png"></image>
				<image v-else-if="device=='测温仪器'" src="../../static/images/tempreture.png"></image>
				<view class="button-container">
				  <button class="button" @click="cancelSearch">取消</button>
				  <button class="button" @click="connectDevice">确认连接</button>
				</view>
			</view>
			<view v-if="connecting">
				<image src="../../static/images/conecting.png"></image>
			</view>
			<view v-if="connectionSuccess || connectionFalid">
				<image v-if="connectionSuccess" src="../../static/images/connection_success.png" alt="连接成功"/>
				<img v-else src="../../static/images/connection_failed.png" alt="连接失败"/>
			</view>
    </view>
  </view>
</template>

<style>
.search-back {
  background-color: white;
  height: 40vh;
}

.search-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.search-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.radar-container {
  margin-bottom: 20px;
}

.bold-text {
  font-weight: bold;
  font-size: 20px;
}

.small-text {
  font-size: 14px;
  color: #999999;
}

.button-container {
  display: flex;
  justify-content: center;
}

.button {
  margin: 10px;
  padding: 10px 20px;
  background-color: #ccc;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
</style>

<script>
export default {
  props: ['device-name'],
	onHide() {
		this.bluetoothDevices=[],
		this.valueList = []
	},
  data() {
    return {
      device: this.deviceName,
			deviceSearch:true,
			deviceFind:false,
      connecting: false,
      connectionSuccess: false,
			connectionFalid:false,
			bluetoothDevices: [], // 存储蓝牙设备列表
			serviceId: "",
			notifyId: "",
			deviceId: "" ,// 0xFFE0，0xFFE1 0xFFE2
			valueList:[], // 这里的话要对第三个数除10
			deviceToConnection:null
    }
  },
  methods: {
    connectDevice() {
      this.handleBluetoothDeviceClick(this.deviceToConnection)
    },
		init() {
			this.deviceSearch=true
			this.deviceFind=false
			this.connecting=false
			this.connectionSuccess=false
			this.connectionFalid=false
			this.bluetoothDevices=[],
			this.valueList=[],
			console.log("初始化成功")
			this.startBluetoothDiscovery()
		},
		// 2.1 开启搜寻功能
		startBluetoothDiscovery() {
			let retryCount = 0;
			console.log("蓝牙搜索中");
			const startDiscovery = () => {
				uni.startBluetoothDevicesDiscovery({
					success: (res) => {
						console.log("蓝牙搜索已启动", res);
						this.listenBluetoothDevices();
					},
					fail: (err) => {
						console.error("启动蓝牙搜索失败", err);
						if (retryCount < 3) {
							retryCount++;
							setTimeout(startDiscovery, 1000); // 一秒后进行重试
						}
					},
				});
			};
			startDiscovery();
			console.log("蓝牙搜索结束");
		},
		// 2.2 监听搜寻到新设备
		listenBluetoothDevices() {
			console.log("开始搜索")
			console.log(this.device)
		  uni.onBluetoothDeviceFound((res) => {
				switch(this.device) {
					case '血压仪器':{
						this.handleConnection(res,"AOJ-30B");
						break;
					}
					case '血氧仪器': {
						this.handleConnection(res,"AOJ-70B");
						break;
					}
					case '测温仪器': {
						this.handleConnection(res,"AOJ-20A");
						break;
					}
					default : {
						console.log("err device")
					}
				}
		  });
		},
		handleConnection(res,deviceInfo) {
			const devices = res.devices;
			this.bluetoothDevices.push(...res.devices);
			for (let i = 0; i < devices.length; i++) {
				// TODO 这里需要对筛选出设备来
			  console.log(
			    "name:" +
			      devices[i].name +
			      " id: " +
			      devices[i].deviceId +
			      ", uuid: " +
			      devices[i].advertisServiceUUIDs
			  );
				if(devices[i].name==deviceInfo){
					this.deviceToConnection = devices[i]
					//this.handleBluetoothDeviceClick(devices[i]);
					// 这里表示设备搜索到了
					this.deviceSearch = false
					this.deviceFind = true
					break;
				}
			}
		},
		// 3 点击进行蓝牙连接
		handleBluetoothDeviceClick(device) {
		  console.log(
		    "点击了蓝牙设备" + device.deviceId + " " + device.advertisServiceUUIDs
		  );
		  this.connectBluetoothDevice(
		    device.deviceId,
		    device.advertisServiceUUIDs[0]
		  ); // 将device.deviceId传递给连接方法
		},
		connectBluetoothDevice(deviceId, serviceUuid) {
		  console.log("待连接的设备id为" + deviceId);
		  uni.createBLEConnection({
		    deviceId: deviceId,
		    success: (res) => {
		      console.log("蓝牙设备连接成功", res);
		      // 断开连接
		      this.stopBluetoothDiscovery();
					this.deviceFind = false
					this.connectionSuccess = true
					// 这里要传递值给父元素
					this.$emit("send",deviceId,serviceUuid)
					// this.getCharacteristics();
		    },
		    fail: (err) => {
		      console.error("蓝牙设备连接失败", err);
					this.connectionFalid = true
		    },
		  });
		},
		stopBluetoothDiscovery() {
		  uni.stopBluetoothDevicesDiscovery({
		    success: (res) => {
		      console.log("蓝牙搜索已停止", res);
		      // this.bluetoothDevices = [];
		    },
		    fail: (err) => {
		      console.error("停止蓝牙搜索失败", err);
		    },
		  });
		},
		closeConnection() {
			console.log("正在断开连接")
			this.getTime()
			uni.closeBLEConnection({
			  deviceId : this.deviceId,
			  success: (res)=>{
			    console.log(res)
					console.log("断开连接成功")
			  },
				fail: (err) => {
					console.log(err)
					console.log("断开连接失败")
				}
			})
		}
  }
}
</script>
